package com.rf.richfitwheel.admin.iam.service.impl;

import com.rf.richfitwheel.admin.conf.IamPropertiesConfig;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.iam.HttpEntityJsonUtil;
import com.rf.richfitwheel.admin.iam.dao.PortalOrgMapper;
import com.rf.richfitwheel.admin.iam.model.*;
import com.rf.richfitwheel.admin.iam.service.PortalOrgService;
import com.rf.richfitwheel.admin.sys.model.Config;
import com.rf.richfitwheel.admin.sys.model.Org;
import com.rf.richfitwheel.admin.sys.service.CodeUseInfoService;
import com.rf.richfitwheel.admin.sys.service.ConfigService;
import com.rf.richfitwheel.admin.sys.service.OrgService;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.utils.UuidUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hushouquan
 */
@Service
public class PortalOrgServiceImpl implements PortalOrgService{
    private Logger log = LoggerFactory.getLogger(PortalOrgServiceImpl.class);
    @Autowired
    private IamPropertiesConfig iamPropertiesConfig;
    @Autowired
    private RestTemplate restTemplateOuter;
    @Autowired
    private ConfigService configService;
    @Autowired
    private PortalOrgMapper portalOrgMapper;
    @Autowired
    private OrgService orgService;
    @Autowired
    private CodeUseInfoService codeUseInfoService;
    
    /**
     * 从门户同步组织机构数据并入库
     *
     * @param appId    在商网注册的集成编号
     * @param myDate   时间戳毫秒值
     * @param config 游标
     * @param countSyn 记录数
     * @return 记录数
     */
    @Override
    public Integer orgSynDo(String appId, long myDate, Config config, Integer countSyn) throws URISyntaxException, IOException{
        //数据同步的游标
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("hostname", iamPropertiesConfig.getHostnameByAppId(appId));
        CloseableHttpResponse response =HttpEntityJsonUtil.executeApi(iamPropertiesConfig.getAccessKeyByAppId(appId),
                iamPropertiesConfig.getSecretKeyByAppId(appId), appId, "GET", null, headerMap,
                iamPropertiesConfig.getUrl() + UrlConstant.IAM_API_ORGS_SYNC, config.getParamValue());
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if(statusCode == org.apache.http.HttpStatus.SC_OK){
            IamReturnOrgSyn iamReturnOrgSyn = HttpEntityJsonUtil.httpEntityContentToJsonArray(entity, IamReturnOrgSyn.class);
            if(iamReturnOrgSyn != null && iamReturnOrgSyn.getCode() == 0){
                PortalOrgSyn portalOrgSyn = iamReturnOrgSyn.getData();
                List<PortalOrg> listOrg = portalOrgSyn.getRecords();
                for(PortalOrg portalOrg : listOrg){
                    portalOrg.setId(UuidUtil.get32UUID());
                    portalOrg.setMyTime(myDate);
                    portalOrgMapper.insert(portalOrg);
                }
                countSyn = countSyn + listOrg.size();
                log.info("已同步{}条组织机构数据", countSyn);
                config.setParamValue(portalOrgSyn.getNext_cursor() + "");
                //如果还有记录的话递归继续执行
                if(portalOrgSyn.isHas_more()){
                    countSyn = orgSynDo(appId, myDate, config, countSyn);
                }
            }else{
                log.warn("调用门户同步机构数据失败：{}", iamReturnOrgSyn);
            }
        }else{
            log.error("调用门户同步机构数据失败：{}", EntityUtils.toString(entity));
        }
        response.close();
        return countSyn;
    }
    
    /**
     * 在数据已同步入库的情况下将数据处理至正式表
     *
     * @param myDate 时间戳毫秒值
     */
    @Override
    public void orgDeal(long myDate) throws Exception{
        PortalOrgExample example = new PortalOrgExample();
        PortalOrgExample.Criteria criteria = example.createCriteria();
        //根据入库时间处理数据
        criteria.andMyTimeEqualTo(myDate);
        List<PortalOrg> portalOrgList = portalOrgMapper.selectByExample(example);
        UserVO user = new UserVO();
        user.setId(Constant.SUPER_ADMIN);
        int count = 0;
        for(PortalOrg portalOrg : portalOrgList){
            Org org = orgService.selectById(portalOrg.getOrgId());
            if(org == null){
                //新增
                org = new Org();
                org.setId(portalOrg.getOrgId());
                org.setVersion(0);
                String orgCode = portalOrg.getSocialCreditCode();
                if(orgCode == null){
                    orgCode = portalOrg.getOrgCode();
                }
                if(orgCode == null){
                    orgCode= portalOrg.getOrgId();
                }
                org.setOrgCode(orgCode);
                org.setOrgName(portalOrg.getOrgName());
                org.setShortName(portalOrg.getOrgShortName());
                org.setTenantId(Constant.SUPER_ADMIN_TENANTID);
                org.setOrgLevel(0);
                org.setParentId(portalOrg.getParentId() == null ? "0" : portalOrg.getParentId());
                if(portalOrg.getStatus() == 2) {
                    org.setOrgStatus(Constant.COMMON_STATUS_DELETED);
                }else{
                    org.setOrgStatus(Constant.COMMON_STATUS_NORMAL);
                }
                org.setOrgType(Constant.OrgType.ORGRANK_PRACTICAL.getValue());
                org.setOrdernum(portalOrg.getSortNumber());
                org.setCreater(Constant.SUPER_ADMIN);
                org.setCreateTime(new Date(myDate));
                org.setType("0");
                if(portalOrg.getOrgType() == 1 && portalOrg.getStatus() == 1){
                    //企业
                    org.setIsParent(Constant.COMMON_YES_OR_NO_YES);
                    org.setOrgRank(Constant.OrgRank.ORGRANK_COMPANY.getValue());
                    //企业下面给默认加一个本部的虚拟机构
                    Org benBu = new Org();
                    benBu.setId(UuidUtil.get32UUID());
                    benBu.setVersion(0);
                    benBu.setOrgCode(org.getOrgCode() + "-01");
                    benBu.setOrgName(portalOrg.getOrgName() + "本部");
                    benBu.setShortName(portalOrg.getOrgShortName() + "本部");
                    benBu.setTenantId(Constant.SUPER_ADMIN_TENANTID);
                    benBu.setOrgLevel(0);
                    benBu.setParentId(org.getId());
                    benBu.setOrgStatus(Constant.COMMON_STATUS_NORMAL);
                    benBu.setOrgType(Constant.OrgType.ORGRANK_VIRTUAL.getValue());
                    benBu.setOrdernum(1);
                    benBu.setCreater(Constant.SUPER_ADMIN);
                    benBu.setCreateTime(new Date(myDate));
                    benBu.setType("0");
                    benBu.setIsParent(Constant.COMMON_YES_OR_NO_YES);
                    benBu.setOrgRank(Constant.OrgRank.ORGRANK_COMPANY.getValue());
                    try{
                        orgService.addOrg(benBu, user);
                    }catch(Exception e){
                        log.error(e.getMessage(), e);
                    }
                }else{
                    //部门
                    org.setIsParent(Constant.COMMON_YES_OR_NO_NO);
                    org.setOrgRank(Constant.OrgRank.ORGRANK_DEPT.getValue());
                }
                try{
                    orgService.addOrg(org, user);
                }catch(Exception e){
                    log.error(e.getMessage(), e);
                }
            }else{
                //修改
                org.setVersion(org.getVersion() + 1);
                String orgCode = portalOrg.getSocialCreditCode();
                if(orgCode == null){
                    orgCode = portalOrg.getOrgCode();
                }
                if(orgCode == null){
                    orgCode= portalOrg.getOrgId();
                }
                org.setOrgCode(orgCode);
                org.setOrgName(portalOrg.getOrgName());
                org.setShortName(portalOrg.getOrgShortName());
                org.setOrgLevel(0);
                org.setParentId(portalOrg.getParentId() == null ? "0" : portalOrg.getParentId());
                if(portalOrg.getStatus() == 2) {
                    org.setOrgStatus(Constant.COMMON_STATUS_DELETED);
                }else{
                    org.setOrgStatus(Constant.COMMON_STATUS_NORMAL);
                }
                org.setOrgType(Constant.OrgType.ORGRANK_PRACTICAL.getValue());
                org.setOrdernum(portalOrg.getSortNumber());
                org.setModUser(Constant.SUPER_ADMIN);
                org.setModTime(new Date(myDate));
                org.setType("0");
                if(portalOrg.getOrgType() == 1){
                    //企业
                    org.setIsParent(Constant.COMMON_YES_OR_NO_YES);
                    org.setOrgRank(Constant.OrgRank.ORGRANK_COMPANY.getValue());
                }else{
                    //部门
                    org.setIsParent(Constant.COMMON_YES_OR_NO_NO);
                    org.setOrgRank(Constant.OrgRank.ORGRANK_DEPT.getValue());
                }
                try{
                    orgService.updateOrg(org, user);
                }catch(Exception e){
                    log.error(e.getMessage(), e);
                }
            }
            count++;
            if(count % 500 == 0 || count == portalOrgList.size()){
                log.info("已处理{}/{}条数据", count, portalOrgList.size());
            }
        }
        log.info("共处理{}条数机构数据", portalOrgList.size());
    }
}
